package com.cskaoyan.controller;

import cn.hutool.core.convert.Convert;

import com.cskaoyan.bean.CskaoyanmallAdmin;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.exceptions.DefinitionException;
import com.cskaoyan.myenum.ResultEnum;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.service.LogService;
import com.cskaoyan.service.PermissionService;
import com.cskaoyan.service.RoleService;
import com.cskaoyan.shiro.LoginToken;
import com.cskaoyan.utils.IpUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;

/**
 * @author Fantasylkh
 */
@RequestMapping("/admin/auth")
@RestController
//后台管理系统登录功能
public class AuthController {

    @Autowired
    AuthService authService;

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;

    @Autowired
    LogService logService;

    @RequestMapping("/login")
    public BaseRespVo login(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String username = Convert.toStr(map.get("username"));
        String password = Convert.toStr(map.get("password"));

        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password)) {
            throw new DefinitionException(611, "账号密码参数错误");
        }

        Subject subject = SecurityUtils.getSubject();


        try {
            //将密码进行加密
            Md5Hash md5Hash = new Md5Hash(password);
            md5Hash.setIterations(1024);
            password = md5Hash.toHex();
            //将页面的帐户密码进行加密后，传进subject,对比数据库的帐户密码
            subject.login(new LoginToken(username, password, "admin"));
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            throw e;
        }

        String adminName = (String) subject.getPrincipal();
        CskaoyanmallAdmin cskaoyanmallAdmin = authService.selectAdminByName(adminName);
        String ipAddr = IpUtils.getIpAddr(request);
        cskaoyanmallAdmin.setLastLoginIp(ipAddr);
        cskaoyanmallAdmin.setLastLoginTime(new Date());
        authService.updateAdmin(cskaoyanmallAdmin);
        Serializable token = subject.getSession().getId();
        return BaseRespVo.success(token);
    }

    @RequestMapping("/info")
    public BaseRespVo info() {
        Subject subject = SecurityUtils.getSubject();
        String principal = (String) subject.getPrincipal();
        CskaoyanmallAdmin cskaoyanmallAdmin = authService.selectAdminByName(principal);
        if (ObjectUtils.isEmpty(cskaoyanmallAdmin)) {
            return BaseRespVo.fail(1);
        }
        Integer[] roleIds = cskaoyanmallAdmin.getRoleIds();

        HashMap<String, Object> res = new HashMap<>();
        res.put("name", cskaoyanmallAdmin.getUsername());
        res.put("avatar", cskaoyanmallAdmin.getAvatar());
        Set<String> roles = roleService.selectRolesByRoleIds(roleIds);
        Set<String> perms = permissionService.selectPermissionsByRoleIds(roleIds);
        res.put("perms", perms);
        res.put("roles", roles);

        return new BaseRespVo<Object>(ResultEnum.SUCCESS, res);
    }

    @PostMapping("/logout")
    public Object logout() {
        Subject subject = SecurityUtils.getSubject();
        String principal = (String) subject.getPrincipal();
        logService.logout(principal);
        subject.logout();
        return BaseRespVo.success();
    }
}
